package com.camel;

import java.util.List;

import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.RouteDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class CamelErrorHandlerTest {

	public static void main(String[] args) throws Exception {
		ApplicationContext appContext = new ClassPathXmlApplicationContext("camel/error-context.xml");
		CamelContext context = appContext.getBean(CamelContext.class);
		/*context.addRoutes(new RouteBuilder() {
			@Override
			public void configure() throws Exception {
				onException(Exception.class).handled(true).process(errorProcessor);
			}
		});*/
		
		context.stop();
		
		List<RouteDefinition> routes = context.getRouteDefinitions();
		for(RouteDefinition route : routes.toArray(new RouteDefinition[routes.size()])) {
			final String routeId = route.getId();
			RouteDefinition routeDef = route.adviceWith(context, new RouteBuilder() {
				public void configure() throws Exception {
					System.out.println("adding error processor for route " + routeId);
					onException(Exception.class).handled(true).process(errorProcessor);
				}
			});
			System.out.println(routeDef);
		}
		
		context.start();
		
		Thread.sleep(100 * 1000);
	}
	
	private static final Processor processor = new Processor() {
		@Override
		public void process(Exchange exchange) throws Exception {
			System.out.println(exchange);
			throw new Exception("Testing error handler");
		}
	};
	
	private static final Processor errorProcessor = new Processor() {
		@Override
		public void process(Exchange exchange) throws Exception {
			System.out.println("Exchange failed: " + exchange);
		}
	};
}
